package com.bosssoft.hr.javase;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Dom4jPaser implements Paser {
    public Student[] parse(String url) throws IOException, DocumentException {
        String s = new HttpFileDownloader().downloadByUrl(url);

        SAXReader reader = new SAXReader();//得到解析器对象
        //通过解析器对象得到文档对象
        Document document = reader.read(new File(FileConf.filepath  + s + ".xml"));
        //得到根节点（此处的根节点是“users”）
        Element root = document.getRootElement(); // <users>
        //得到子节点“users”的子节点“user”的迭代器
        Iterator<Element> userElements = root.elementIterator(); // <user></user>...<user></user>
        List<Student> list = new ArrayList<Student>();
        while (userElements.hasNext()) {
            Element userElement = userElements.next(); // <user></user>
            String id = userElement.attribute("id").getStringValue(); // <id>value</id>
            String name = userElement.element("name").getStringValue();
            list.add(new Student(Integer.valueOf(id), name));
        }
        return list.toArray(new Student[] {}); // new ClassName[] {}
    }

    public static void main(String[] args) throws IOException, DocumentException {
        Student[] students = new Dom4jPaser().parse("http://58.22.61.222:57903/javasexml/user.xml");
        for (Student u : students) {
            System.out.println(u.getId() + " " + u.getName());
        }
    }
}
